# -*- encoding: utf-8 -*-

"""
@File:      tc_python_pyyaml_fun_002.py
@Time:      Thu Sep 21 2023 16:47:33
@Author:    ylsong
@Version:   1.0
@Contact:   songyl157@chinaunicom.cn
@License:   Mulan PSL v2
@Modify:    ylsong
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_python_pyyaml_fun_002.yaml for details

    :avocado: tags=P1,noarch,local,python
    """
    PARAM_DIC = {"pkg_name": ""}
    def setUp(self):
        super().setUp(self.PARAM_DIC)

    def test(self):
        self.cmd('pip3 install pyyaml')
        cmdline = '''cat > test.py  << EOF
#!/usr/bin/python
# -- coding: UTF-8 --
import os,sys
import yaml
def generate_yaml_doc(yaml_file):
    py_object = {'school': 'zhang','students': ['a', 'b']}
    file = open(yaml_file, 'w')
    yaml.dump(py_object, file)
    file.close()
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "generate.yaml")
generate_yaml_doc(yaml_path)
EOF'''
        self.cmd(cmdline)
        cmdline = '''cat > test1.py  << EOF
#!/usr/bin/python
# -- coding: UTF-8 --
import yaml
import os
def get_yaml_data(yaml_file):
    # 打开yaml文件
    print("获取yaml文件数据")
    file = open(yaml_file, 'r')
    file_data = file.read()
    file.close()
    print(file_data)
    print("类型：", type(file_data))
    # 将字符串转化为字典或列表
    print("转化yaml数据为字典或列表")
    data = yaml.safe_load(file_data)
    print(data)
    print("类型：", type(data))
    return data
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "generate.yaml")
get_yaml_data(yaml_path)
EOF'''
        self.cmd(cmdline)
        self.cmd("python3 test.py")
        code,result=self.cmd("cat generate.yaml")
        self.assertIn("school: zhang",result)
        self.assertIn("students",result)
        code,result=self.cmd("python3 test1.py")
        self.assertIn("school: zhang",result)
        self.assertIn("{'school': 'zhang', 'students': ['a', 'b']}",result)


    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf test.py test1.py")